#include "stdafx.h"
#include "GSE_CConnector.h"
#include "GSE_CSession.h"
namespace GSE
{
	CConnector::CConnector(io_service & ios):m_IOService(ios),m_tcpResolver(m_IOService),m_lpSession(new CSession(m_IOService))
	{
	}

	CConnector::~CConnector()
	{
	}

	void CConnector::Connect( const char * strIP, const char * strPort )
	{
		ip::tcp::resolver::query query(strIP, strPort);
		m_tcpResolver.async_resolve(query,bind(&CConnector::AsyncResolve,shared_from_this(), placeholders::error,placeholders::iterator));
	}

	void CConnector::AsyncResolve( const system::error_code& errCode,ip::tcp::resolver::iterator iterator )
	{
		if ( !errCode )
		{
			m_EndPoint = *iterator;
			AsyncConnect();
		}
		else
		{
			m_lpSession->GetCallbackPtr()->OnError(errCode.value(),errCode.message().c_str());
		}
	}

	void CConnector::SetSessionCallback( ISessionCallback * lpCallback )
	{
		m_lpSession->SetCallback(lpCallback);
	}

	ISession* CConnector::GetSession()
	{
		return m_lpSession.get();
	}

	void CConnector::OnConnected( const system::error_code& errCode )
	{
		m_lpSession->OnConnected(errCode);
	}

	void CConnector::AsyncConnect()
	{
		m_lpSession->GetSocket().async_connect(m_EndPoint, bind(&CConnector::OnConnected,shared_from_this(), placeholders::error));
	}

	uint CConnector::Run()
	{
		return m_IOService.poll();
	}
}